import { AddRoleModel } from '@/api/role/RoleModel'
import { EditType, Title } from '@/type/BaseEnum'
import { DialogModel } from '@/type/BaseType'
import { ElForm } from 'element-plus'
import { nextTick, reactive, ref } from 'vue'
import useInstance from '@/hooks/useInstance'

export default function useAddRole (
  dialog: DialogModel,
  onClose,
  onShow,
  emit
) {
  const { global } = useInstance()

  const addRoleForm = ref<InstanceType<typeof ElForm>>()

  // 表单绑定的数据
  const addModel = reactive<AddRoleModel>({
    id: '',
    name: '',
    createUser: '',
    type: '',
    remark: ''
  })

  // 表单验证规则
  const rules = reactive({
    name: [
      {
        trigger: 'change',
        required: true,
        message: '请填写角色名称'
      }
    ]
  })

  // 确定
  const confirm = () => {
    console.log('点击了确认')

    addRoleForm.value?.validate(valid => {
      if (valid) {
        console.log('验证通过')

        emit('save', addModel)
        onClose()
      } else {
        console.log('验证没有通过')
      }
    })
  }
  // 显示弹框
  const show = (type: string, row: AddRoleModel) => {
    dialog.height = 180
    type == EditType.ADD
      ? (dialog.title = Title.ADD)
      : (dialog.title = Title.EDIT)
    onShow()
    global.$resetForm(addRoleForm.value, addModel)
    //如果是编辑，复制当前行到表单绑定的数据
    if (type == EditType.EDIT) {
      console.log('检测到是编辑', row)
      nextTick(() => {
        global.$objCoppy(row, addModel)
      })
    }
    //设置编辑属性
    addModel.type = type
  }
  return {
    confirm,
    show,
    addModel,
    rules,
    addRoleForm
  }
}
